<template>
  <el-dialog title="修改密码" :visible.sync="dialogVisible" width="40%" :close-on-click-modal="false">
    <el-form ref="dataForm" :rules="modelRules" :model="model" label-width="100px">
      <el-form-item label="新密码" prop="password">
        <el-tooltip v-model="capsTooltip" content="大写锁定已开启" placement="top" manual>
          <el-input :key="isPasswordType" v-model="model.password" :type="isPasswordType?'password':''" placeholder="新密码" @keyup.native="checkCapslock" @blur="capsTooltip = false">
            <template slot="append">
              <span class="show-pwd" @click="isPasswordType = !isPasswordType">
                <svg-icon :icon-class="isPasswordType ? 'eye' : 'eye-open'" />
              </span>
            </template>
          </el-input>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input :key="isPasswordType" v-model="model.confirmPassword" :type="isPasswordType?'password':''" placeholder="确认密码" @keyup.native="checkCapslock" @blur="capsTooltip = false">
          <template slot="append">
            <span class="show-pwd" @click="isPasswordType = !isPasswordType">
              <svg-icon :icon-class="isPasswordType ? 'eye' : 'eye-open'" />
            </span>
          </template>
        </el-input>
      </el-form-item>
      <!-- <el-form-item prop="shouldChangePasswordOnNextLogin">
        <el-checkbox v-model="model.shouldChangePasswordOnNextLogin">下次登录需要修改密码</el-checkbox>
      </el-form-item> -->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="info" style="float:left;" @click="randomPassword()">随机生成密码</el-button>
      <el-button @click="close()">取消</el-button>
      <el-button type="primary" :loading="isSubmitLoading" @click="save()">提交</el-button>
    </div>
  </el-dialog>
</template>
<script>
import abp from 'abp'
import { changePassword } from "@/api/identity/user";

export default {
  data() {
    const validatePassword = (rule, value, callback) => {
      const givenPassword = value;
      if (!givenPassword || givenPassword.length < 0) {
        callback(new Error(`请输入密码`));
      }

      const requiredLength = this.passwordComplexitySetting.requiredLength;
      if (requiredLength && givenPassword && givenPassword.length < requiredLength) {
        callback(new Error(`密码至少需要${requiredLength}个字符`));
      }

      const requireDigit = this.passwordComplexitySetting.requireDigit;
      if (requireDigit && givenPassword && !/[0-9]/.test(givenPassword)) {
        callback(new Error(`密码必须包含数字`));
      }

      const requireUppercase = this.passwordComplexitySetting.requireUppercase;
      if (requireUppercase && givenPassword && !/[A-Z]/.test(givenPassword)) {
        callback(new Error(`密码必须包含大写字母`));
      }

      const requireLowercase = this.passwordComplexitySetting.requireLowercase;
      if (requireLowercase && givenPassword && !/[a-z]/.test(givenPassword)) {
        callback(new Error(`密码必须包含小写字母`));
      }

      const requireNonAlphanumeric = this.passwordComplexitySetting.requireNonAlphanumeric;
      if (requireNonAlphanumeric && givenPassword && /^[0-9a-zA-Z]+$/.test(givenPassword)) {
        callback(new Error(`密码必须包含标点符号`));
      }

      callback();
    };

    const validateConfirmPassword = (rule, value, callback) => {
      const givenPassword = value;

      if (givenPassword !== this.model.password) {
        callback(new Error(`确认密码和密码必须一致`));
      }

      callback();
    };
    return {
      passwordComplexitySetting: {
        requiredLength: abp.setting.getInt('Abp.Identity.Password.RequiredLength'),
        requireDigit: abp.setting.getBoolean('Abp.Identity.Password.RequireDigit'),
        requireUppercase: abp.setting.getBoolean('Abp.Identity.Password.RequireUppercase'),
        requireLowercase: abp.setting.getBoolean('Abp.Identity.Password.RequireLowercase'),
        requireNonAlphanumeric: abp.setting.getBoolean('Abp.Identity.Password.RequireNonAlphanumeric'),
        requiredUniqueChars: abp.setting.getInt('Abp.Identity.Password.RequiredUniqueChars')
      },
      isPasswordType: true,
      capsTooltip: false,

      dialogVisible: false,
      isSubmitLoading: false,
      id: undefined,
      model: {
        password: "",
        confirmPassword: ""
        // shouldChangePasswordOnNextLogin: false
      },
      modelRules: {
        password: [{ required: true, trigger: "blur", validator: validatePassword }],
        confirmPassword: [{ required: true, trigger: "blur", validator: validateConfirmPassword }]
        // shouldChangePasswordOnNextLogin: [{ required: true }]
      }
    };
  },
  methods: {
    show(id) {
      this.resetModal();
      this.id = id;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    resetModal() {
      this.model = {
        password: "",
        confirmPassword: ""
        // shouldChangePasswordOnNextLogin: false
      };
    },
    randomPassword() {
      this.isPasswordType = false;

      var password = [];
      const length = 8;
      const passwordArray = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz', '1234567890', '~!@#$%&*()'];
      for (let index = 0; index < length; index++) {
        var arrayRandom = Math.floor(Math.random() * 4);
        if (index < 4) {
          arrayRandom = index;// 先从大写 小写 数字 字符中 各取一个
        }

        const passwordItem = passwordArray[arrayRandom];
        const item = passwordItem[Math.floor(Math.random() * passwordItem.length)];
        const spliceIndex = Math.floor(Math.random() * password.length);
        password.splice(spliceIndex, 0, item);
      }
      this.model.password = password.join("");
      this.model.confirmPassword = this.model.password;
    },
    save() {
      this.isSubmitLoading = true;
      this.$refs["dataForm"].validate(valid => {
        if (!valid) {
          this.isSubmitLoading = false;
          this.$message({ message: this.$t("formIsNotValidMessage"), type: "warning" });
          return;
        }

        changePassword(this.id, this.model)
          .then(() => {
            this.$message({ message: "修改成功", type: "success" });
            this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
            this.close();
          })
          .finally(() => {
            this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
          });
      });
    },
    close() {
      this.dialogVisible = false;
      this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
    },
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if ((shiftKey && (key >= "a" && key <= "z")) || (!shiftKey && (key >= "A" && key <= "Z"))) {
          this.capsTooltip = true;
        } else {
          this.capsTooltip = false;
        }
      }
      if (key === "CapsLock" && this.capsTooltip === true) {
        this.capsTooltip = false;
      }
    }
  }
};
</script>
